package com.ruoyi.basedata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.basedata.domain.TerminalsDb;
import com.ruoyi.basedata.domain.TerminalsXb;
import com.ruoyi.basedata.domain.UsersXb;
import com.ruoyi.basedata.mapper.RoomMapper;
import com.ruoyi.basedata.mapper.TerminalsDbMapper;
import com.ruoyi.basedata.mapper.TerminalsXbMapper;
import com.ruoyi.basedata.mapper.UsersXbMapper;
import com.ruoyi.basedata.service.IUsersXbService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 小用户档案Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-07
 */
@Service
@Slf4j
public class UsersXbServiceImpl implements IUsersXbService
{
    @Autowired
    private UsersXbMapper usersXbMapper;

    @Autowired
    private TerminalsXbMapper terminalsXbMapper;

    @Autowired
    private TerminalsDbMapper terminalsDbMapper;

    /**
     * 查询小用户档案
     *
     * @param ID 小用户档案主键
     * @return 小用户档案
     */
    @Override
    public UsersXb selectUsersXbByID(Long ID)
    {
        return usersXbMapper.selectUsersXbByID(ID);
    }

    /**
     * 查询小用户档案列表
     *
     * @param usersXb 小用户档案
     * @return 小用户档案
     */
    @Override
    public List<UsersXb> selectUsersXbList(UsersXb usersXb)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (Objects.equals(user.getSystemFlag(), Constants.SYS_FLAG_NORMAL_USER)){
            usersXb.setTenantId(user.getTenantId());
        }
        return usersXbMapper.selectUsersXbList(usersXb);
    }

    @Override
    public List<UsersXb> selectUsersXbList(Collection<String> userIdList) {
        return usersXbMapper.selectList(new LambdaQueryWrapper<UsersXb>()
                .in(!CollectionUtils.isAnyEmpty(),UsersXb::getUserId,userIdList));
    }

    /**
     * 新增小用户档案
     *
     * @param usersXb 小用户档案
     * @return 结果
     */
    @Override
    public int insertUsersXb(UsersXb usersXb)
    {
        List<UsersXb> usersXbs = usersXbMapper.selectList(new LambdaQueryWrapper<UsersXb>()
                .eq(usersXb.getUserId() != null, UsersXb::getUserId, usersXb.getUserId()));
        if (usersXbs.size() == 0){
            usersXb.setCreateTime(DateUtils.getNowDate());
            usersXb.setUserMark(1);
            usersXb.setDelFlag(0);
            return usersXbMapper.insertUsersXb(usersXb);
        }
        return 0;
    }

    /**
     * 修改小用户档案
     *
     * @param usersXb 小用户档案
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUsersXb(UsersXb usersXb) {
        UsersXb exist = usersXbMapper.selectOne(new LambdaQueryWrapper<UsersXb>()
                .eq(UsersXb::getUserId, usersXb.getUserId()));
        if (exist == null) {
            UsersXb beforeUpdate = usersXbMapper.selectById(usersXb.getId());
            int rows = usersXbMapper.updateUsersXb(usersXb);
            if (rows > 0) {
                // 同步修改大表档案里的user_id
                LambdaQueryWrapper<TerminalsDb> dbUpdateWrapper = Wrappers.lambdaQuery();
                dbUpdateWrapper.eq(TerminalsDb::getUserId, beforeUpdate.getUserId());
                TerminalsDb dbUpdate = new TerminalsDb();
                dbUpdate.setUserId(usersXb.getUserId());
                terminalsDbMapper.update(dbUpdate, dbUpdateWrapper);
                // 同步修改小表档案里的user_id
                LambdaQueryWrapper<TerminalsXb> xbUpdateWrapper = Wrappers.lambdaQuery();
                xbUpdateWrapper.eq(TerminalsXb::getUserId, beforeUpdate.getUserId());
                TerminalsXb xbUpdate = new TerminalsXb();
                xbUpdate.setUserId(usersXb.getUserId());
                terminalsXbMapper.update(xbUpdate, xbUpdateWrapper);
            }
            return rows;
        }
        if (Objects.equals(exist.getId(), usersXb.getId())) {
            return usersXbMapper.updateUsersXb(usersXb);
        }
        return 0;
    }

    /**
     * 批量删除小用户档案
     *
     * @param IDs 需要删除的小用户档案主键
     * @return 结果
     */
    @Override
    public int deleteUsersXbByIDs(Long[] IDs)
    {
        // List<Long> deleteList = new ArrayList<>();
        // Arrays.stream(IDs).forEach(id ->{
        //     Integer count = terminalsXbMapper.countByUserId(id);
        //     if (count == 0){
        //         deleteList.add(id);
        //     }
        // });
        // if (deleteList.size()==0){
        //     return 0;
        // }
        return usersXbMapper.deleteBatchIds(Arrays.asList(IDs));
    }

    /**
     * 删除小用户档案信息
     *
     * @param ID 小用户档案主键
     * @return 结果
     */
    @Override
    public int deleteUsersXbByID(Long ID)
    {
        return usersXbMapper.deleteById(ID);
    }

    @Override
    public String importUser(List<UsersXb> list, boolean updateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (UsersXb usersXb : list)
        {
            try
            {
                // 验证是否存在这个表用户
                List<UsersXb> usersXbList = usersXbMapper.selectList(new LambdaQueryWrapper<UsersXb>()
                        .eq(UsersXb::getUserId, usersXb.getUserId()));
                if(null != usersXbList && usersXbList.size()>0){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、用户编号 " + usersXb.getUserId() + " 已存在");
                }else {
                    usersXb.setCreateTime(DateUtils.getNowDate());
                    usersXb.setUserMark(1);
                    usersXb.setDelFlag(0);
                    usersXbMapper.insertUsersXb(usersXb);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、用户编号 " + usersXb.getUserId() + " 更新成功");
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、用户编号 " + usersXb.getUserId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
